package com.lhq.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lhq.gulimall.product.service.CategoryBrandRelationService;
import com.lhq.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhq.common.utils.PageUtils;
import com.lhq.common.utils.Query;

import com.lhq.gulimall.product.dao.CategoryDao;
import com.lhq.gulimall.product.entity.CategoryEntity;
import com.lhq.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /***
     *   查出所有分类，并组装成父子的树形结构
     * @return java.util.List<com.lhq.gulimall.product.entity.CategoryEntity>
     * @Author lianghanqiang
     * @Date 2022/10/15 15:00
     **/
    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> level1Menus = null;
        RLock lock = redissonClient.getLock("category:tree");
        lock.tryLock();
        try {
            // 查出所有分类
            List<CategoryEntity> entities = baseMapper.selectList(null);

            // 组装父子的树形结构
            // 找到所有的一级分类
            level1Menus = entities.stream().filter(categoryEntity ->
                    categoryEntity.getParentCid() == 0
            ).map(menu -> {
                menu.setChildren(getChildrens(menu, entities));
                return menu;
            }).sorted((menu1, menu2) -> {
                return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null ? 0:menu2.getSort());
            }).collect(Collectors.toList());

        }catch (Exception e){
            lock.unlock();
        }

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前使用的菜单， 是否在别的地方被引用

        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();

        List<Long> parentPaths = findParentPaths(catelogId, paths);

        Collections.reverse(parentPaths);

        return (Long[]) parentPaths.toArray(new Long[parentPaths.size()]);
    }

    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);

        if(StringUtils.isNotEmpty(category.getName())){
            categoryBrandRelationService.upcateCategory(category.getCatId(), category.getName());
        }
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));

        return categoryEntities;
    }

    /**
     * 1. 空结果缓存，并设置过期时间： 解决缓存穿透
     * 2.设置过期时间（加随机值）： 解决缓存雪崩
     * 3. 加锁： 解决缓存击穿
     *
     * @return
     */
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        // 给缓存中存的是json字符串，拿出的json字符串，还要逆转为能用的对象类型 【序列化与反序列化的过程】
        Map<String, List<Catelog2Vo>> catalogJsonEntities = null;
        // 1.加入缓存逻辑，缓存中存的数据是json字符串
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String catalogJSON = ops.get("catalogJSON");
        if(StringUtils.isEmpty(catalogJSON)){
            // 缓存中没有， 查询数据库
            catalogJsonEntities = getCatalogJsonFromDb();
            // 查到的数据放入缓存,将对象转为json放入缓存中
            String jsonString = JSON.toJSONString(catalogJsonEntities);
            ops.set("catalogJSON", jsonString,1, TimeUnit.DAYS);
        }else{
            catalogJsonEntities = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        }
        return catalogJsonEntities;
    }
    /***
     *从数据库查询并封装分类数据
     * @return java.util.Map<java.lang.String,java.util.List<com.lhq.gulimall.product.vo.Catelog2Vo>>
     * @Author lianghanqiang
     * @Date 2023/2/4 12:09
     **/
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {
        Map<String, List<Catelog2Vo>> parent_cid = null;

        // 本地锁 synchronized JUC（lock）  只锁当前服务的进程
        // 在分布式情况下，想要锁住所有，就必须使用分布式锁
        // synchronized (this) {
        //     // 得到锁以后， 应该再去缓存中确定一次，如果没有才需要继续查询
        //     Map<String, List<Catelog2Vo>> catalogJsonEntities = null;
        //     // 1.加入缓存逻辑，缓存中存的数据是json字符串
        //     ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //     String catalogJSON = ops.get("catalogJSON");
        //     if(StringUtils.isNotEmpty(catalogJSON)){
        //         return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        //     }
        //
        //     List<CategoryEntity> selectList = baseMapper.selectList(null);
        //     // 1.查出所有一级分类
        //     List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //
        //     // 2.封装数据
        //     parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> {
        //         return k.getCatId().toString();
        //     }, v -> {
        //         // 1.每一个的一级分类，查到总共一级分类的二级分类
        //         List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
        //         // 2.封装上面的结果
        //         List<Catelog2Vo> catelog2Vos = null;
        //         if (categoryEntities != null) {
        //             catelog2Vos = categoryEntities.stream().map(l2 -> {
        //                 Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());
        //                 // 1.找当前二级分类的三级分类封装成vo
        //                 List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
        //
        //                 if(level3Catelog != null){
        //                     List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
        //                         // 2.封装成指定格式
        //                         Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());
        //                         return catelog3Vo;
        //                     }).collect(Collectors.toList());
        //                     catelog2Vo.setCatalog3List(collect);
        //
        //                 }
        //                 return catelog2Vo;
        //             }).collect(Collectors.toList());
        //         }
        //         return catelog2Vos;
        //     }));
        //
        // }

        // 分布式锁（redis实现）
        String s = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", s);
        if(lock){
            log.info("获取分布式锁成功");
            // 加锁成功
            stringRedisTemplate.expire("lock",300,TimeUnit.SECONDS);

            try {
                Map<String, List<Catelog2Vo>> catalogJsonEntities = null;
                // 1.加入缓存逻辑，缓存中存的数据是json字符串
                ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
                String catalogJSON = ops.get("catalogJSON");
                if(StringUtils.isNotEmpty(catalogJSON)){
                    return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>(){});
                }

                List<CategoryEntity> selectList = baseMapper.selectList(null);
                // 1.查出所有一级分类
                List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

                // 2.封装数据
                parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> {
                    return k.getCatId().toString();
                }, v -> {
                    // 1.每一个的一级分类，查到总共一级分类的二级分类
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
                    // 2.封装上面的结果
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {
                        catelog2Vos = categoryEntities.stream().map(l2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());
                            // 1.找当前二级分类的三级分类封装成vo
                            List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                            if(level3Catelog != null){
                                List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                                    // 2.封装成指定格式
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(collect);

                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catelog2Vos;
                }));
            }finally {
                // 删除锁也需要原子操作  lua 脚本
                String lua = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(lua, Long.class),
                        Arrays.asList("lock"), s);
                log.info("删除分布式锁"+(lock1==0L?"失败":"成功"));
            }
        }else{
            // 加锁失败。。。 重试
            log.info("获取分布式锁失败，等待重试");
            // 休眠200ms
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return  getCatalogJsonFromDb();
        }

        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPaths(Long categoryId, List<Long> paths){
        // 收集当前节点id
        paths.add(categoryId);
        CategoryEntity byId = this.getById(categoryId);
        if(byId.getParentCid() != 0){
            findParentPaths(byId.getParentCid(),paths);
        }
        return paths;
    }

    /***
     *  递归查找所有菜单的子菜单
     *
     * @param entity
     * @param all
     * @return java.util.List<com.lhq.gulimall.product.entity.CategoryEntity>
     * @Author lianghanqiang
     * @Date 2022/10/15 15:24
     **/
    private List<CategoryEntity> getChildrens(CategoryEntity entity, List<CategoryEntity> all) {
        List<CategoryEntity> childrens = all.stream().filter(categoryEntity ->
                categoryEntity.getParentCid().equals(entity.getCatId())
        ).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2)->{
            return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null ? 0:menu2.getSort());
        }).collect(Collectors.toList());

        return childrens;
    }

}